const App = getApp()
const api = require('../../../utils/api.js');
const util = require('../../../utils/util.js');


Page({
  data: {
    //取消订单添加备注
    remark_cancel: '',
    modalHidden_cancle: true,

    modalHidden: true,
    firstIndex: 0,
    firstList: [],
    secondList: [],
    tapType: "",
    secondIndex: 0,
    num: "",
    prompt: {
      hidden: !0,
      icon: '../../../assets/images/iconfont-order-default.png',
      title: '您还没有相关的订单',
      text: '可以去看看有哪些想买的',
    },
    //页面渲染数据
    windowWidth: wx.getSystemInfoSync().screenWidth,
    windowHeight: wx.getSystemInfoSync().windowHeight,
    order_id: '',
    external_order_no: '',
    toastHidden: true,
    rps_data: {
      doc_url: {},
      list: [],
      page: {
        page_no: 0,
        page_size: 5,
      },
      paginate: {}
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */

  onShow: function () {

    //停止之前的倒计时
    console.log("***onShow***********************")
    clearTime(interval)

    this.initData(),//初始化数据
      this.getOrderList(true);

  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    console.log("***onHide***********************")
    clearTime(interval)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    console.log("***onUnload***********************")
    clearTime(interval)
  },


  onLoad: function (options) {
    this.setData({
      //再宅急送数据未接入的情况下，
      // firstList: [
      //       {
      //         name: '淘淘领',
      //         _id: 'taotaoling',
      //       },
      //       {
      //         name: '宅急送',
      //         _id: 'zhaijisong',
      //       }
      //   ],
      tapType: App.globalData.status,
      secondIndex: App.globalData.secondIndex,
      secondList: [
        {
          name: '全部',
          _id: 'all',
        },
        {
          name: '待付款',
          _id: 'processing',
        },
        {
          name: '待返款',
          _id: 'confirmed',
        },
        {
          name: '已返款',
          _id: 'closed',
        },
        {
          name: '已取消',
          _id: 'cancelled',
        }
      ]
    })

    /*         //停止之前的倒计时
            console.log("**************************")
    
            clearTime(interval)
            this.getOrderList(true); */
  },

  //初始化数据
  initData() {
    this.setData({
      rps_data: {
        doc_url: {},
        list: [],
        page: {
          page_no: 0,
          page_size: 5,
        },
        paginate: {}
      }
    })
  },


  //拉到底部刷新
  onPullDownRefresh() {
    console.info('onPullDownRefresh')
    if (!this.data.rps_data.paginate.hasNext) return

    console.log("****onPullDownRefresh**********************")

    //停止之前的倒计时
    clearTime(interval)
    this.getOrderList(true)
  },

  //获取订单列表
  getOrderList(countdown) {
    const self = this;

    let pageData = {
      page_no: this.data.rps_data.page.page_no + 1,
      page_size: this.data.rps_data.page.page_size,
    }

    let data = {
      page: JSON.stringify(pageData),
      service: 'order.smallprogram.fgOrderListPageFind',
      params: '{"status":"all","member_id":""}',
      url_type: 'opsorder',
      app_token: App.globalData.app_token,
      security_code: App.globalData.security_code

    }

    //标签状态切换查询
    var json = JSON.parse(data.params);
    json.member_id = App.globalData.memberInfo.member_id;
    //let firstIndex: self.data.firstIndex
    //let secondIndex: self.data.firstIndex


    //submitOrder页面跳转
    if (self.data.tapType == "all" || self.data.tapType == "") {
      delete json.status;
      data.params = JSON.stringify(json);
    } else {
      json["status"] = self.data.tapType
      data.params = JSON.stringify(json);
    }

    //let sign = util.getSign(data);
    //data.sign = sign;

    var rps_data = this.data.rps_data

    api.reqData({
      data,
      success: (res) => {

        console.log(">>>>>>>>>>> 订单结果 >>>>>>>>>>>>>>>>>>>>>>>>>>>>")
        console.log(res)

        var list;
        //过滤接口返回得数据 _id和字码值得转化
        if (res.data.rsp_code != 'fail') {
          list = res.data.data.list;

          for (var i = 0; i < list.length; i++) {
            if (list[i].status == "processing") {
              list[i].status = 1;
            } else if (list[i].status == "confirmed") {
              list[i].status = 2;
            } else if (list[i].status == "closed") {
              list[i].status = 3;
            } else if (list[i].status == "cancelled") {
              list[i].status = 4;
            }
            //格式化超时时间
            //list[i].diff_time = self.dateformat(list[i].diff_time)
            //根据order_Type区分自营(meitianhui:1)和淘宝商品(taobao:0),会过商品（huiguo:2）
            if (list[i].order_type == 'meitianhui') {
              list[i].order_type = 1
            } else if (list[i].order_type == 'huiguo') {
              list[i].order_type = 2
            } else {
              list[i].order_type = 0
            }
            //根据订单时间获得预计返款时间
            //list[i]['order_return_date'] = self.GetDateStr(list[0].order_date, 2);


          }


          //订单头像图片展示  doc_url和里面头像分离
          let list_new = util.mergePic(res.data.data.doc_url, list);
          rps_data.list = [...rps_data.list, ...list_new]

          //预先处理下数据
          for (var i = 0; i < rps_data.list.length; i++) {
            //处理下时间
            if (rps_data.list[i].diff_time > 1000) {
              rps_data.list[i].diff_timeStr = date_format(rps_data.list[i].diff_time) ////包含“分钟、秒”的时间字符串
            }
          }


          rps_data.page.page_no = res.data.data.page.page_no
          rps_data.page.page_size = res.data.data.page.page_size
          //paginate.total_page = res.data.data.page.total_page
          rps_data.paginate.total_count = res.data.data.page.total_count
          //判断hasNext
          if (rps_data.paginate.total_count > rps_data.page.page_no * rps_data.page.page_size) {
            console.log("后面有数据 还没有查询完")
            rps_data.paginate.hasNext = true
          } else {
            console.log("后面没有数据了，不要再拉了")
            rps_data.paginate.hasNext = false
          }

          console.log(rps_data);
          self.setData({
            rps_data: rps_data,
          })


          //倒计时
          if (countdown) {
            interval = setInterval(() => {
              count_down(self);
            }, 1000);
          }



        }
      },
    })
  },

  //根据当前时间获得两天后时间
  /*     GetDateStr(nowTimeStr,AddDayCount) {
        var dd = new Date(nowTimeStr);
        dd.setDate(dd.getDate() + AddDayCount);//获取AddDayCount天后的日期 
        var y = dd.getFullYear();
        var m = dd.getMonth() + 1;//获取当前月份的日期 
        var d = dd.getDate();
        var h = dd.getHours();
        var mi = dd.getMinutes();
        var se = dd.getSeconds();
        return y + "-" + m + "-" + d + ' ' + h + ':' + mi + ':' + se;
      }, */

  // 时间格式化输出，如11:03 25:19 每1s都会调用一次
  /*     dateformat(NowTime) {
        if (NowTime <= 0) {
          return "已经截至";
        };
        var that = this
        // 秒数  
        var second = Math.floor(NowTime / 1000);
        // 小时位  
        var hr = Math.floor(second / 3600);
        // 分钟位  
        var min = that.fill_zero_prefix(Math.floor((second - hr * 3600) / 60));
        // 秒位  
        var sec = that.fill_zero_prefix(second % 60);// equal to => var sec = second % 60;  
  
        return min + "分钟" + sec + "秒";
      }, */

  /* 分秒位数补0 */
  /*     fill_zero_prefix(num) {
        return num < 10 ? "0" + num : num
      }, */

  //查看物流 h5页面跳转测试
  viewLogistics(e) {
    wx.request({
      url: 'https://appportal.meitianhui.com/openapi/h5/c/hpt/logistics',
      data: {
        logistics_number: '3851520138945'
      },
      header: {
        'content-type': 'application/json' // 默认值
      },
      success: function (res) {
        console.log(res.data)
      }
    })
  },


  //tab标签的互动切换
  onTapTag_First(e) {
    const type = e.currentTarget.dataset.type
    const index = e.currentTarget.dataset.index
    //this.initData()
    this.setData({
      firstIndex: index,
      //二级tab归零
      secondIndex: 0,
      tapType: type,
    })
    //停止之前的倒计时
    if (interval > 0) {
      console.log("clearInterval")
      clearInterval(interval);
      console.log(interval)
    }
    this.getOrderList(true)
  },

  onTapTag_Second(e) {
    const type = e.currentTarget.dataset.type
    const index = e.currentTarget.dataset.index

    this.initData(),
      this.setData({
        secondIndex: index,
        tapType: type,
      })
    //停止之前的倒计时
    if (interval > 0) {
      console.log("clearInterval")
      clearInterval(interval);
      console.log(interval)
    }
    if (index == 0 || index == 1) {
      this.getOrderList(true)
    } else {
      this.getOrderList(false)
    }
  },

  navigateTo(e) {
    console.log(e)
    App.WxService.navigateTo('/pages/order/detail/index', {
      id: e.currentTarget.dataset.id
    })
  },

  //确定订单页面弹出半透明窗口js
  confirmOrder: function (e) {
    let order_id = e.currentTarget.dataset.id;
    this.setData({
      modalHidden: false,
      order_id: order_id,
      external_order_no: ''
    })
  },

  //取消订单页面弹出半透明窗口js
  cancelOrder: function (e) {
    let order_id = e.currentTarget.dataset.id;
    //let remark_cancel = this.data.remark_cancel;
    this.setData({
      remark_cancel: '',
      modalHidden_cancle: false,
      order_id: order_id
    })
  },

  //取消订单
  modalChange_cancel: function (e) {
    this.setData({
      modalHidden_cancle: true
    })
    //调用确定订单接口
    const self = this;
    let data = {
      service: 'order.fgOrderCancelled',
      params: '{"order_id":"595d85028e3e43098d9f1f52fa2bfeca","remark":"错误","data_source":"SJLY_01"}',
      url_type: 'opsorder',
      app_token: App.globalData.app_token,
      security_code: App.globalData.security_code
    }

    var json = JSON.parse(data.params);
    json["order_id"] = self.data.order_id;
    json["remark"] = self.data.remark_cancel;
    data.params = JSON.stringify(json);

    //let sign = util.getSign(data);
    //data.sign = sign;

    api.reqData({
      data,
      success: (res) => {
        console.log(res.data + "---------------------------");
        if (res.data.rsp_code === "succ") {
          this.setData({
            secondIndex: 4,
            tapType: "cancelled"
          })
          this.initData()
          //停止之前的倒计时
          if (interval > 0) {
            console.log("clearInterval")
            clearInterval(interval);
            console.log(interval)
          }
          this.getOrderList(true)
        }
      },
    })
  },

  //确定订单
  modalChange: function (e) {
    this.setData({
      modalHidden: true
    })
    //调用确定订单接口
    const self = this;
    let data = {
      service: 'order.fgOrderConfirm',
      params: '{"order_id":"df11183f073941f3b1f826907273ed9f","external_order_no":"245588854445888574","data_source":"SJLY_01"}',
      url_type: 'opsorder',
      app_token: App.globalData.app_token,
      security_code: App.globalData.security_code
    }

    var json = JSON.parse(data.params);
    json["order_id"] = self.data.order_id;
    json["external_order_no"] = self.data.external_order_no;
    data.params = JSON.stringify(json);

    //let sign = util.getSign(data);
    //data.sign = sign;

    api.reqData({
      data,
      success: (res) => {
        console.log(res.data + "---------------------------");
        if (res.data.rsp_code === "succ") {
          this.setData({
            secondIndex: 2,
            tapType: "confirmed",
            num: res.data.qty
          })
          this.initData()
          //停止之前的倒计时
          clearInterval(interval);
          this.getOrderList(true)
        }
      },
    })
  },

  //确定订单对话框取消按钮
  modalChange1: function (e) {
    console.log(">>>>>>>>>>>>>>>>>>>>>>>>>>   modalChange1   >>>>>>>>>>>>***********************************")
    console.log(e)


    this.setData({
      modalHidden: true
    })
  },

  //取消订单对话框取消按钮
  modalChange1_cancel: function (e) {
    this.setData({
      modalHidden_cancle: true
    })
  },

  //获取输入的淘宝订单号
  externalOrderNoInput: function (e) {
    this.setData({
      external_order_no: e.detail.value
    })
  },

  //获取取消订单备注
  remarkInput: function (e) {
    this.setData({
      remark_cancel: e.detail.value
    })
  },

  //设置淘淘领变量到剪贴版
  toCost(e) {
    let product_source = e.target.id;
    let order_type = e.currentTarget.dataset.hi;
    App.globalData.order_data = e.currentTarget.dataset.hii;
    if (order_type == 0) {
      wx.setClipboardData({
        data: product_source,
        success: function (res) {
          console.log(res)
        }
      }),
        //弹出窗口
        this.setData({
          toastHidden: false,
        })
    } else {
      wx.navigateTo({
        url: '../resubmitOrder/resubmitOrder?num=' + e.currentTarget.dataset.hii.item_qty
      })
    }


  },

  modalChange2: function (e) {
    this.setData({
      toastHidden: true,
    })
  },


})




var interval;


/* 秒级倒计时 */
function count_down(that) {


  //成批渲染倒计时时钟
  for (var i = 0; i < that.data.rps_data.list.length; i++) {

    var diff_time = that.data.rps_data.list[i].diff_time;//毫秒级
    var diff_timeKey = 'rps_data.list[' + i + '].diff_time';
    var diff_timeStrKey = 'rps_data.list[' + i + '].diff_timeStr';//包含“分钟、秒”的时间字符

    if (diff_time >= 0) {

      that.setData({
        [diff_timeKey]: that.data.rps_data.list[i].diff_time
      });

      console.log("第" + i + "   interval>>" + interval + "    time>>> " + diff_time)

      that.setData({
        [diff_timeStrKey]: date_format(that.data.rps_data.list[i].diff_time)
      });

      that.data.rps_data.list[i].diff_time = that.data.rps_data.list[i].diff_time - 1000;

      //如果其中有时间是“已经截止”，重新再刷新
      if (that.data.rps_data.list[i].diff_time <= 0 &&
        that.data.rps_data.list[i].diff_time >= -1000) {
        //停止之前的倒计时
        clearInterval(interval);
        that.initData();
        that.getOrderList(true);
      }

    }
  }
};


// 时间格式化输出，传入的time为毫秒级
function date_format(time) {

  if (time <= 1000) {
    return "已经截止";
  };

  // 秒数  
  var second = Math.floor(time / 1000);
  // 小时位
  var hr = Math.floor(second / 3600);
  // 分钟位  
  var min = Math.floor((second - hr * 3600) / 60);
  // 秒位  
  var sec = (second % 60);// equal to => var sec = fill_zero_prefix((second - hr * 3600 - min * 60));

  if (hr != '00') {
    return hr + "小时" //+ min + "分钟" + sec + "秒";
  } if (min == '0') {
    return sec + "秒"
  } else {
    return min + "分钟" + sec + "秒";
  }
};

// 位数不足补零
/* function fill_zero_prefix(num) {
  return num < 10 ? "0" + num : num
}; */


function clearTime(interval) {

  if ((interval != undefined && interval != null) && interval > 0) {
    console.log("clearInterval")
    clearInterval(interval);
    console.log(interval)
  }

}